package com.solarsmile.gallery.view.fragment


import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.os.Bundle
import android.os.Handler
import android.view.*
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.solarsmile.gallery.R
import com.solarsmile.gallery.adapter.GalleryAdapter
import com.solarsmile.gallery.viewmodel.GalleryViewModel
import com.solarsmile.gallery.viewmodel.NET_WORK_ERROR
import kotlinx.android.synthetic.main.dialog.view.*
import kotlinx.android.synthetic.main.fragment_gallery.*

/**
 * A simple [Fragment] subclass.
 */
val keyWords = arrayOf("cat", "panda", "dog", "car", "bird", "sunshine", "computer")

class GalleryFragment : Fragment() {
    lateinit var galleryAdapter: GalleryAdapter
    private lateinit var galleryViewModel: GalleryViewModel
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_gallery, container, false)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {      //加载菜单项
        super.onCreateOptionsMenu(menu, inflater)
        inflater.inflate(R.menu.menu, menu)  //加载菜单布局
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {  //设置菜单选项的点击事件
        when (item.itemId) {
            R.id.swipeIndicator -> {
//                swipeRefreshLayout.isRefreshing = true
//                Handler().postDelayed(Runnable {
//                    //延迟1秒再显示
//                    galleryViewModel.loadMore()
//                }, 1000)
            }
        }
        return super.onOptionsItemSelected(item)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        setHasOptionsMenu(true)  //设置加载菜单
        addfab1.visibility = View.GONE  //  搜索
        addfab2.visibility = View.GONE  //  刷新
        addfab3.visibility = View.GONE  //  返回顶部
        galleryViewModel = ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory(requireActivity().application)
        ).get(GalleryViewModel::class.java)
        galleryAdapter = GalleryAdapter(galleryViewModel)
        recyclerView.apply {
            adapter = galleryAdapter
            layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        }
        galleryViewModel.gallery.observe(viewLifecycleOwner, Observer {
            if (galleryViewModel.scrollToTop) {
                recyclerView.scrollToPosition(0)
                galleryViewModel.scrollToTop = false
            }
            galleryAdapter.submitList(it)  //给galleryAdapter填充数据
            swipeRefreshLayout.isRefreshing = false  //下拉刷新获取完数据后停止刷新状态
        })
        galleryViewModel.dataStatus.observe(viewLifecycleOwner, Observer {
            galleryAdapter.footViewStatus = it
            galleryAdapter.notifyItemChanged(galleryAdapter.itemCount - 1)
            if (it == NET_WORK_ERROR) swipeRefreshLayout.isRefreshing = false
        })
        galleryViewModel.gallery.value
            ?: galleryViewModel.loadMore()  //判断galleryViewModel中是否有数据，没有就直接获取
        swipeRefreshLayout.setOnRefreshListener {
            //下拉刷新
            //galleryViewModel.loadMore()
            swipeRefreshLayout.isRefreshing = false
        }
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            @SuppressLint("RestrictedApi")
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (dy < 0) {
                    floatingActionButton.visibility =
                        View.VISIBLE  //dy<0证明是向下划，此时FloatingActionButton处于于显示状态
                    addfab1.visibility = View.GONE  //  搜索
                    addfab2.visibility = View.GONE  //  刷新
                    addfab3.visibility = View.GONE  //  返回顶部
                    return
                }
                if (dy > 0) {
                    floatingActionButton.visibility =
                        View.GONE //dy>0证明是向上划，此时FloatingActionButton处于隐藏状态
                    addfab1.visibility = View.GONE  //  搜索
                    addfab2.visibility = View.GONE  //  刷新
                    addfab3.visibility = View.GONE  // 返回顶部
                }
                val layoutManager = recyclerView.layoutManager as StaggeredGridLayoutManager
                val intArray = IntArray(2)
                layoutManager.findLastVisibleItemPositions(intArray)
                if (intArray[0] == galleryAdapter.itemCount - 1) {
                    galleryViewModel.fetchData()
                }
            }
        })
        floatingActionButton.setOnClickListener {
            recyclerView.stopScroll()  // 点击FloatingActionButton时停止RecyclerView的滚动
            // 设置FloatingActionButton
            if (addfab1.isVisible) {
                addfab1.visibility = View.GONE  //  搜索
                addfab2.visibility = View.GONE  //  刷新
                addfab3.visibility = View.GONE  //  返回顶部
            } else {
                addfab1.visibility = View.VISIBLE  //  搜索
                addfab2.visibility = View.VISIBLE  //  刷新
                addfab3.visibility = View.VISIBLE  //  返回顶部
            }
        }
        //  搜索按钮
        addfab1.setOnClickListener {
            var dialogview: View =
                LayoutInflater.from(requireContext()).inflate(R.layout.dialog, null)
            addfab1.visibility = View.GONE  //  搜索
            addfab2.visibility = View.GONE  //  刷新
            addfab3.visibility = View.GONE  //  返回顶部
            AlertDialog.Builder(requireContext()).setView(dialogview).setTitle("搜索")
                .setPositiveButton("确定", DialogInterface.OnClickListener { dialog, which ->
                    var stringkey = dialogview.editText.text.toString()
                    galleryViewModel.loadMore(stringkey)
                    galleryViewModel.gallery.observe(viewLifecycleOwner, Observer {
                        galleryAdapter.submitList(it)
                        galleryAdapter.notifyDataSetChanged()
                    })
                }).setNeutralButton("取消", null).create().show()
        }

        //  刷新按钮
        addfab2.setOnClickListener {
            galleryViewModel.loadMore()
            addfab1.visibility = View.GONE  //  搜索
            addfab2.visibility = View.GONE  //  刷新
            addfab3.visibility = View.GONE  //  返回顶部
        }

        //  返回顶部按钮
        addfab3.setOnClickListener {
            recyclerView.scrollToPosition(0)
            addfab1.visibility = View.GONE  //  搜索
            addfab2.visibility = View.GONE  //  刷新
            addfab3.visibility = View.GONE //  返回顶部
        }
    }
}
